#include <iostream>
#include <string>
#include <cstring>
#include <string.h>
#include <cerrno>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <arpa/inet.h>

void Usage(char *proc)
{
    std::cout << "Usage:\n\t" << proc << " server.ip server.port" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 0;
    }

    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        std::cerr << "socket failed" << errno << std::endl;
        return 1;
    }
    std::cout << "socket success" << std::endl;

    uint16_t ser_port = atoi(argv[2]);
    std::string ser_addr = argv[1];
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(ser_port);
    server.sin_addr.s_addr = INADDR_ANY;
    //server.sin_addr.s_addr = inet_addr(ser_addr.c_str());

    if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0)
    {
        std::cerr << "connnect failed" << errno << std::endl;
        return 2;
    }
    std::cout << "connect success" << std::endl;

    while (true)
    {
        std::cout << "请输入指令";
        char command[1024] = {0};
        fgets(command, sizeof(command), stdin);

        write(sock, command, strlen(command));
        char buffer[1024] = {0};

        ssize_t size = read(sock, buffer, sizeof(buffer));
        if (size > 0){
            buffer[size] = 0;
            std::cout << buffer << std::endl;
        }
    }
}